import React from "react"
import {Button, Divider, message, Modal, PageHeader, Popconfirm, Table, Tag} from "antd";
import {ArrowLeftOutlined, ClockCircleOutlined, ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import cs from "classnames";
import SearchAutoComplete from "libs/search-auto-complete"
import {useRequest} from '@umijs/hooks'
import {orderType, pageSetting} from "project-config"
import {formatResult, useTableCheck} from "../../shared/libs/hooks/table-hooks"
import {get} from "server"
import {del, putJSON} from "../../shared/server"

import {clearner} from "../../shared/libs/utils"
import highlight from "../../shared/libs/highlight"

const {confirm} = Modal;

const Account = (props) => {

	const {role, roleName} = props

	const onDelete = (id) => {
		del(`/management/account/admin/${id}`).then((data) => {
			if (data) {
				message.success('用户删除成功')
				onSearch()
			}
		})
	}
	const enableAccount = (row) => {
		putJSON(`/management/account/admin/${row.enabled ? "disable" : "enable"}/${row.id}`).then((data) => {
			if (data) {
				message.success(data.enabled ? "启用成功" : "禁用成功")
				onSearch()
			}
		})
	}
	const updateAccount = (id) => {
		props.history.push(`/app/account/${role||'admin'}/edit/${id}`)
	}
	//获取数据
	const getPageData = ({current, pageSize, sorter, filters, searchKey}) => {
		let enabled;
		if (filters && filters.enabled && filters.enabled.length === 1) {
			enabled = filters.enabled[0];
		}
		let sortKey;
		let sortType;
		if (sorter && sorter.columnKey && sorter.order) {
			sortKey = sorter.columnKey;
			sortType = orderType[sorter.order];
		}
		return get(`/management/account/admin/${pageSize}/${current}`, clearner({
			searchKey,
			role,
			sortType,
			sortKey,
			enabled
		}))
	}
	//表格选中
	const {rowSelection, items} = useTableCheck({})
	const {tableProps, params, refresh, pagination} = useRequest(getPageData, {
		paginated: true,
		defaultPageSize: 10,
		formatResult,
	})
	const onSearch = (searchKey) => {
		params[0].searchKey = searchKey
		params[0].role = role
		refresh().finally()
	}
	const resetPassword = (id) => {
		putJSON(`/management/account/admin/reset/${id}`).then((data) => {
			if (data) {
				message.success("重置密码成功")
				onSearch()
			}
		})
	}
	const onDeleteBatch = () => {
		if (items != null) {
			del(`/management/account/admin/batch/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功删除 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}
	const onEnabledBatch = () => {
		if (items != null) {
			putJSON(`/management/account/admin/batch/enable/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功启用 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}
	const onDisabledBatch = () => {
		if (items != null) {
			putJSON(`/management/account/admin/batch/disable/${items.join(',')}`).then(result => {
				if (result) {
					message.success(`成功禁用 ${items.length} 条用户`)
					onSearch()
				}
			})
		}
	}
	const showConfirm = (handle) => {
		const batchMapping = {
			Delete: {
				key: "删除",
				func: onDeleteBatch
			},
			Enabled: {
				key: "启用",
				func: onEnabledBatch
			},
			Disabled: {
				key: "禁用",
				func: onDisabledBatch
			},
		}
		confirm({
			title: `确认${batchMapping[handle].key}`,
			icon: <ExclamationCircleOutlined/>,
			content: `确认要${batchMapping[handle].key}以下${items.length}记录?`,
			onOk() {
				batchMapping[handle].func();
			},
			onCancel() {
			},
		});
	}
	const accountColumns = [
		{
			title: '登录名',
			key: 'loginName',
			dataIndex: 'loginName',
			width: 150,
			render: (v) => highlight(v, params[0].searchKey)
		}, {
			title: '姓名',
			key: 'name',
			width: 150,
			dataIndex: 'name',
			render: (v) => highlight(v, params[0].searchKey)
		}, {
			title: '手机号',
			key: 'phoneNo',
			dataIndex: 'phoneNo',
			render: (v) => highlight(v, params[0].searchKey)
		}, {
			title: '状态',
			key: 'enabled',
			dataIndex: 'enabled',
			filters: [
				{text: "启用", value: true},
				{text: "禁用", value: false}
			],
			render: (text) => text ? <Tag color="#4CAF50" className={'large'}>启用中</Tag> : <Tag className={'large'} color="#f50">禁用中</Tag>
		}, {
			title: '最后登录时间',
			key: 'lastLoginTime',
			dataIndex: 'lastLoginTime',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: (text) => text && <Tag className="large"><ClockCircleOutlined/> {text}</Tag>
		}, {
			title: '创建时间',
			key: 'createTime',
			dataIndex: 'createTime',
			sorter: true,
			showSorterTooltip: false,
			sortDirections: ['ascend', 'descend', 'ascend'],
			render: (text) => text && <Tag className="large"><ClockCircleOutlined/> {text}</Tag>
		}, {
			title: '操作',
			key: 'action',
			width: 240,
			render: (_, record) => (
				<>
					<a onClick={() => updateAccount(record.id)}>编辑</a>
					<Divider type="vertical"/>
					<Popconfirm
						title={`确定要${record.enabled ? "禁用" : "启用"}此账号吗?`}
						placement="rightBottom"
						onConfirm={() => enableAccount(record)}
					>
						<a>{record.enabled ? "禁用" : "启用"}</a>
					</Popconfirm>
					<Divider type="vertical"/>
					<Popconfirm
						title={`确定要重置密码吗，重置后将为初始密码?`}
						placement="rightBottom"
						onConfirm={() => resetPassword(record.id)}
					>
						<a>重置密码</a>
					</Popconfirm>
					<Divider type="vertical"/>
					<Popconfirm
						title="确定要注销此账号吗?"
						placement="rightBottom"
						onConfirm={() => onDelete(record.id)}
					>
						<a>注销</a>
					</Popconfirm>
				</>
			)
		}
	]

	const btnPrpos = {
		type: 'primary',
		disabled: items.length < 1,
		ghost: true,
		style: {marginLeft: 10}
	}

	return (
		<div className={'zr-panel'}>
			<div className={'zr-panel-header'}>
				<PageHeader backIcon={<ArrowLeftOutlined/>} onBack={() => window.history.back()} title={`${roleName || '管理员'}管理`} subTitle=''/>
			</div>
			<div className={' zr-list-page-box body-bg body-border absolute'}>
				<div className={cs(' zr-query-box')} style={{paddingRight: '20px'}}>
					<SearchAutoComplete style={{marginRight: 10}} allowClear={true} onSelect={onSearch} placeholder="登录名/手机号/姓名查询"/>
					<Button style={{marginLeft: 10}} type="primary" onClick={() => props.history.push(`/app/account/${role || 'admin'}/add`)}>
						<PlusOutlined/>{`添加${roleName || '管理员'}`}
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Enabled")}
					>
						批量启用
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Disabled")}
					>
						批量禁用
					</Button>
					<Button
						{...btnPrpos}
						onClick={() => showConfirm("Delete")}
						danger
					>
						批量删除
					</Button>

				</div>
				<div className={' zr-table-box'}>
					<Table
						{...tableProps}
						pagination={{
							...pagination,
							...pageSetting
						}}
						rowSelection={rowSelection}
						rowKey={record => record.id}
						size=' middle'
						columns={accountColumns}/>
				</div>
			</div>
		</div>
	)
}

export default Account